package com.cwx.tools;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cwx.common.SystemEnums;
import com.cwx.common.Vector;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Request;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by code on 17-7-18.
 */
@Slf4j
public class TB {
    public static Vector getQrCode() throws IOException {
        String generateQRUrl = "https://qrlogin.taobao.com/qrcodelogin/generateQRCode4Login.do?adUrl=&adImage=&adText=&viewFd4PC=&viewFd4Mobile=&from=tbTop&_ksTS=" + Instant.now().toEpochMilli() + "_2838&callback=jsonp2839";
            HttpURLConnection generateQRConn = HttpUrlConnectionUtil.getUrlConnection(generateQRUrl);
            String resultStr = HttpUrlConnectionUtil.readData(generateQRConn, "utf-8");
            resultStr = resultStr.substring(22, resultStr.length() - 7);
            JSONObject result = JSONObject.parseObject(resultStr);
            if (result.getBoolean("success")) {
                String lgToken = result.getString("lgToken");
                String imgUrl = result.getString("url");

                Request build = new Request.Builder().url("https:" + imgUrl).build();
                byte[] bytes = OKHttpUtils.client.newCall(build).execute().body().bytes();

                HashMap<String, Object> map = new HashMap<>();
                map.put("qrcode", Base64.getEncoder().encodeToString(bytes));
                map.put("lgToken", lgToken);

                return new Vector(SystemEnums.SUCCESS.ordinal(), "success", map);
            } else {
                log.error("登录验证码生成失败...");
                return new Vector(SystemEnums.GETDATA_ERROR.ordinal(), "qrcode get fail", null);
            }
    }

    public static Vector scanStatus(String lgToken) throws IOException {

            String loginCheckUrl = "https://qrlogin.taobao.com/qrcodelogin/qrcodeLoginCheck.do?lgToken=" + lgToken + "&defaulturl=https%3A%2F%2Fwww.taobao.com%2F&_ksTS=" + System.currentTimeMillis() + "_89&callback=jsonp90";
            HttpURLConnection checkConn = HttpUrlConnectionUtil.getUrlConnection(loginCheckUrl);
            String checkStr = HttpUrlConnectionUtil.readData(checkConn, "utf-8");
            checkStr = checkStr.substring(20, checkStr.length() - 7);
            JSONObject check = JSONObject.parseObject(checkStr);
            if (check.getBoolean("success")) {
                boolean isTrue = false;
                String checkCode = check.getString("code");
                switch (checkCode) {
                    case "10000":
                        log.info("用户尚未扫码...");
                        return new Vector(SystemEnums.STATUS_1.ordinal(), "用户尚未扫码", null);
                    case "10004":
                        log.error("二维码失效...");
                        return new Vector(SystemEnums.STATUS_1.ordinal(), "二维码失效", null);
                    case "10001":
                        log.info("用户扫描成功,尚未确认登录...");
                        return new Vector(SystemEnums.STATUS_1.ordinal(), "用户扫描成功,尚未确认登录", null);
                    case "10006":
                        log.info("用户已确认登录...");
                        String loginByImUrl = check.getString("url");
                        HttpURLConnection loginByImConn = HttpUrlConnectionUtil.getUrlConnection(loginByImUrl);
                        loginByImConn.setInstanceFollowRedirects(false);
                        String cookie = HttpUrlConnectionUtil.getCookies(loginByImConn);
                        log.info("cookie:" + cookie);
                        return new Vector(SystemEnums.SUCCESS.ordinal(), "用户已确认登录", cookie);
                }
                return new Vector(SystemEnums.STATUS_1.ordinal(), "unknown code", null);
            } else {
                return new Vector(SystemEnums.GETDATA_ERROR.ordinal(), "data get fail", null);
            }
    }

    /**
     * 淘宝基本信息
     *
     * @param cookie
     * @return
     * @throws IOException
     */
    public static String getBasicInfo(String cookie) throws IOException {
            JSONObject basicInfo = new JSONObject();
            String securityUrl = "https://member1.taobao.com/member/fresh/account_security.htm";
            String baseInfoUrl = "https://i.taobao.com/user/baseInfoSet.htm";
            String idCardInfoUrl = "https://member1.taobao.com/member/fresh/certify_info.htm";
            HttpURLConnection securityConn = HttpUrlConnectionUtil.getUrlConnection(securityUrl);
            securityConn.setRequestProperty("Cookie", cookie);
            String securityHtml = HttpUrlConnectionUtil.readData(securityConn, "gbk");
            Document securityDoc = Jsoup.parse(securityHtml);
            Elements gridMsgs = securityDoc.getElementsByClass("grid-msg");
            String userName = gridMsgs.get(0).text();//会员名
            String email = gridMsgs.get(1).text().equals("您尚未设置登录邮箱") ? " " : gridMsgs.get(1).text();//邮箱
            String phone = gridMsgs.get(2).text();//绑定手机号
            String securityLevel = securityDoc.getElementsByClass("zhx-anquan-level-middle").get(0).text();//安全等级
            Element identityElement = securityDoc.getElementsByClass("state").first();
            Element overElement = identityElement.getElementsByClass("over").first();
            String identityStatus = "未完成";//是否实名
            String channel = "";//认证渠道
            String idCard = "";//身份证号
            String realName = "";//真实姓名
            if (overElement != null) {
                identityStatus = overElement.text();//是否实名
            }
            if (identityStatus.equals("已完成")) {
                HttpURLConnection idcardConn = HttpUrlConnectionUtil.getUrlConnection(idCardInfoUrl);
                idcardConn.setRequestProperty("Cookie", cookie);
                String idCardHtml = HttpUrlConnectionUtil.readData(idcardConn, "gbk");
                Document idCardDoc = Jsoup.parse(idCardHtml);
                Elements explainInfos = idCardDoc.getElementsByClass("explain-info");
                channel = explainInfos.get(0).getElementsByClass("left").get(0).text();
                realName = explainInfos.get(2).getElementsByClass("left").get(0).text();
                idCard = explainInfos.get(3).getElementsByClass("left").get(0).text();
            }
            HttpURLConnection baseInfoConn = HttpUrlConnectionUtil.getUrlConnection(baseInfoUrl);
            baseInfoConn.setRequestMethod("POST");
            baseInfoConn.setRequestProperty("Cookie", cookie);
            String baseInfoHtml = HttpUrlConnectionUtil.readData(baseInfoConn, "gbk");
            Document baseInfoDoc = Jsoup.parse(baseInfoHtml);
            String nickName = baseInfoDoc.getElementById("J_uniqueName-mask").val();//昵称
            Elements yearOptions = baseInfoDoc.getElementById("J_Year").getElementsByTag("option");
            String year = yearOptions.select("[selected=selected").first().text();
            Elements monthOptions = baseInfoDoc.getElementById("J_Month").getElementsByTag("option");
            String month = monthOptions.select("[selected=selected").first().text();
            Elements dayOptions = baseInfoDoc.getElementById("J_Date").getElementsByTag("option");
            String day = dayOptions.select("[selected=selected").first().text();
            Element manELement = baseInfoDoc.getElementById("J_gender1");
            String gender = "";//性别
            if (manELement.attr("checked").equals("checked")) {
                gender = "男";
            } else {
                gender = "女";
            }
            basicInfo.put("userName", userName);
            basicInfo.put("email", email);
            basicInfo.put("phone", phone);
            basicInfo.put("securityLevel", securityLevel);
            basicInfo.put("channel", channel);
            basicInfo.put("identityStatus", identityStatus);
            basicInfo.put("idCard", idCard);
            basicInfo.put("realName", realName);
            basicInfo.put("nickName", nickName);
            basicInfo.put("gender", gender);
            basicInfo.put("birthDay", year + "-" + month + "-" + day);

        return basicInfo.toJSONString();
    }

    /**
     * 获取绑定支付宝信息
     * @param cookie
     * @return
     * @throws IOException
     */
    public static String getAlipayInfo(String cookie) throws IOException {
        JSONObject alipayInfo = new JSONObject();
        String hbInfoUrl = "https://i.taobao.com/my_taobao_api/getHuaBeiBalance.json?_ksTS=" + System.currentTimeMillis() + "_581";
        String alipayInfoUrl = "https://member1.taobao.com/member/fresh/account_management.htm";
        String alipayBlanceUrl = "https://i.taobao.com/my_taobao_api/alipay_blance.json?_ksTS=" + System.currentTimeMillis() + "_697";
        HttpURLConnection alipayInfoConn = HttpUrlConnectionUtil.getUrlConnection(alipayInfoUrl);
        alipayInfoConn.setRequestProperty("Cookie",cookie);
        String alipayInfoHtml = HttpUrlConnectionUtil.readData(alipayInfoConn,"gbk");
        Document alipayInfoDoc = Jsoup.parse(alipayInfoHtml);
        String userName = "";//账号
        String email = "";//绑定邮箱
        String mobile = "";//绑定手机
        String realName = "";//绑定的真实姓名
        String idCard = "";//绑定的身份证号
        String status = "未认证";//实名认证状态
        String balance = "";//账户余额
        String yebBalance = "";//余额宝余额
        String yebIncome = "";//余额宝历史收益
        String hbTotal = "";//花呗消费额度
        String hbAvailable = "";//花呗剩余额度
        Elements amountEle = alipayInfoDoc.getElementsByClass("red");
        if (amountEle != null && amountEle.size() > 0){
            userName = amountEle.first().text();
        }
        Elements tbody = alipayInfoDoc.getElementsByTag("tbody");
        if (tbody != null && tbody.size() > 0){
            Elements trs = tbody.first().getElementsByTag("tr");
            Elements firstTds = trs.get(0).getElementsByTag("td");
            email = firstTds.first().text();
            Elements secondTds = trs.get(1).getElementsByTag("td");
            mobile = secondTds.first().text();
            Elements thirdTds = trs.get(3).getElementsByTag("td");
            String userInfo = thirdTds.first().text();
            if (userInfo.contains("已认证")){
                int index = userInfo.indexOf("|");
                realName = userInfo.substring(0,index).trim();
                idCard = userInfo.substring(index + 1,userInfo.length()-3).trim();
                status = "已认证";
            }
        }
        HttpURLConnection hbConn = HttpUrlConnectionUtil.getUrlConnection(hbInfoUrl);
        hbConn.setRequestProperty("Cookie",cookie);
        String hbResultStr = HttpUrlConnectionUtil.readData(hbConn,"utf-8");
        JSONObject hbResult = JSONObject.parseObject(hbResultStr);
        if (hbResult.containsKey("data")){
            JSONObject data = hbResult.getJSONObject("data");
            if (data.containsKey("huaBeiCreditAmount")){
                String huaBeiCreditAmount = data.getString("huaBeiCreditAmount");
                String end = huaBeiCreditAmount.substring(huaBeiCreditAmount.length() - 2);
                hbAvailable = huaBeiCreditAmount.substring(0,huaBeiCreditAmount.length() - 2) + "." + end;
            }
            if (data.containsKey("huaBeiTotalCreditAmount")){
                String huaBeiTotalCreditAmount = data.getString("huaBeiTotalCreditAmount");
                String end = huaBeiTotalCreditAmount.substring(huaBeiTotalCreditAmount.length() - 2);
                hbTotal = huaBeiTotalCreditAmount.substring(0,huaBeiTotalCreditAmount.length() - 2) + "." + end;
            }
        }
        HttpURLConnection alipayBlanceConn = HttpUrlConnectionUtil.getUrlConnection(alipayBlanceUrl);
        alipayBlanceConn.setRequestProperty("Cookie",cookie);
        String blanceResultStr = HttpUrlConnectionUtil.readData(alipayBlanceConn,"utf-8");
        JSONObject blanceResult = JSONObject.parseObject(blanceResultStr);
        if (blanceResult.containsKey("data")){
            JSONObject data = blanceResult.getJSONObject("data");
            if (data.containsKey("balance")){
                balance = data.getString("balance");
            }
            if (data.containsKey("totalProfit")){
                yebIncome = data.getString("totalProfit");
            }
            if (data.containsKey("totalQuotient")){
                yebBalance = data.getString("totalQuotient");
            }
        }
        alipayInfo.put("userName",userName);
        alipayInfo.put("email",email);
        alipayInfo.put("mobile",mobile);
        alipayInfo.put("realName",realName);
        alipayInfo.put("idCard",idCard);
        alipayInfo.put("status",status);
        alipayInfo.put("balance",balance);
        alipayInfo.put("yebBalance",yebBalance);
        alipayInfo.put("yebIncome",yebIncome);
        alipayInfo.put("hbTotal",hbTotal);
        alipayInfo.put("hbAvailable",hbAvailable);
        return alipayInfo.toJSONString();
    }

    /**
     * 获取收货地址信息
     * @param cookie
     * @return
     * @throws IOException
     */
    public static String getReceiptAddress(String cookie) throws IOException{
        JSONArray addresses = new JSONArray();
        String addressUrl = "https://member1.taobao.com/member/fresh/deliver_address.htm";
        HttpURLConnection addressConn = HttpUrlConnectionUtil.getUrlConnection(addressUrl);
        addressConn.setRequestProperty("Cookie",cookie);
        String resultHtml = HttpUrlConnectionUtil.readData(addressConn,"gbk");
        Document document = Jsoup.parse(resultHtml);
        Elements addressInfoEles = document.getElementsByClass("thead-tbl-address");
        if (addressInfoEles != null && addressInfoEles.size() > 0){
            for (Element addressInfo : addressInfoEles){
                JSONObject address = new JSONObject();
                Elements tds = addressInfo.getElementsByTag("td");
                String name = tds.get(0).text();
                String addressStr = tds.get(1).text() + tds.get(2).text();
                String zipCode = tds.get(3).text();
                String phone = tds.get(4).text();
                address.put("name",name);
                address.put("addressStr",addressStr);
                address.put("zipCode",zipCode);
                address.put("phone",phone);
                addresses.add(address);
            }
        }
        return addresses.toJSONString();
    }

    /**
     * 获取订单信息
     * @param cookie
     * @return
     * @throws IOException
     */
    public static String getOrderInfo(String cookie) throws IOException{
        JSONArray orderInfos = new JSONArray();
        String orderUrl = "https://buyertrade.taobao.com/trade/itemlist/asyncBought.htm?action=itemlist/BoughtQueryAction&event_submit_do_query=1&_input_charset=utf8";
        Map<String,String> params = new HashMap<>();
        params.put("pageSize","100");
        for (int pageNum = 1; pageNum < 10; pageNum++){
            HttpURLConnection orderConn = HttpUrlConnectionUtil.getUrlConnection(orderUrl);
            params.put("pageNum",String.valueOf(pageNum));
            orderConn.setRequestProperty("Cookie",cookie);
            orderConn.setRequestMethod("POST");
            orderConn.setRequestProperty("Referer","https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm");
            HttpUrlConnectionUtil.writeData(orderConn,HttpUtils.mapToPostData(params));
            String resultStr = HttpUrlConnectionUtil.readData(orderConn,"gbk");
            JSONObject result = JSONObject.parseObject(resultStr);
            if (result.containsKey("error") && result.getString("error").length() == 0){
                JSONArray mainOrders = result.getJSONArray("mainOrders");
                for (int i = 0; i < mainOrders.size(); i++){
                    JSONObject orderInfo = new JSONObject();//订单信息
                    JSONArray commoditys = new JSONArray();//商品信息
                    JSONObject mainOrder = mainOrders.getJSONObject(i);
                    JSONObject payInfo = mainOrder.getJSONObject("payInfo");
                    JSONObject basicOrderInfo = mainOrder.getJSONObject("orderInfo");
                    JSONObject statusInfo = mainOrder.getJSONObject("statusInfo");
                    JSONArray basicCommoditys = mainOrder.getJSONArray("subOrders");
                    String orderTime = basicOrderInfo.getString("createTime");//订单时间
                    String orderId = basicOrderInfo.getString("id");//订单号
                    String orderAmount = payInfo.getString("actualFee");//订单金额
                    String orderStatus = statusInfo.getString("text");//订单状态
                    for (int j = 0; j < basicCommoditys.size(); j++){
                        JSONObject commodity = new JSONObject();
                        JSONObject basicCommodity = basicCommoditys.getJSONObject(j);
                        JSONObject itemInfo = basicCommodity.getJSONObject("itemInfo");
                        JSONObject priceInfo = basicCommodity.getJSONObject("priceInfo");
                        String title = itemInfo.getString("title");//商品标题
                        String commodityId = itemInfo.getString("id");//商品ID
                        String url = itemInfo.getString("itemUrl");//商品URL
                        String price = priceInfo.getString("realTotal");//商品单价
                        String quantity = basicCommodity.getString("quantity");//商品数量
                        commodity.put("commodityId",commodityId);
                        commodity.put("title",title);
                        commodity.put("url",url);
                        commodity.put("price",price);
                        commodity.put("quantity",quantity);
                        commoditys.add(commodity);
                    }
                    orderInfo.put("orderTime",orderTime);
                    orderInfo.put("orderId",orderId);
                    orderInfo.put("orderAmount",orderAmount);
                    orderInfo.put("orderTime",orderTime);
                    orderInfo.put("orderStatus",orderStatus);
                    orderInfo.put("commoditys",commoditys);

//                JSONArray operations = statusInfo.getJSONArray("operations");
//                JSONObject wuliuInfo = operations.getJSONObject(0);
                    /**
                     * 订单物流信息未完成 TODO
                     */
//                if (statusInfo != null && statusInfo.containsKey("url")){
//                    String wuliuUrl = statusInfo.getString("url");
//                    HttpURLConnection wuliuConn = HttpUrlConnectionUtil.getUrlConnection("https:" + wuliuUrl);
//                    wuliuConn.setRequestProperty("Cookie",cookie);
//                    String resultHtml = HttpUrlConnectionUtil.readData(wuliuConn,"gbk");
//                    Document wuliuDoc = Jsoup.parse(resultHtml);
//                    if (wuliuUrl.startsWith("//trade.tmall.com")){
//                        Elements elements = wuliuDoc.getElementsByTag("script ");
////                        String unresolvedStr = elements.first().text();
////                        unresolvedStr = unresolvedStr.substring("var detailData =".length(),unresolvedStr.length() - 1);
//                    }else if (wuliuUrl.startsWith("//trade.taobao.com")){
//                        Elements elements = wuliuDoc.select("script:contains(var data)");
////                        String unresolvedStr = elements.first().text();
////                        unresolvedStr = unresolvedStr.substring("var data =".length(),unresolvedStr.length() - 1);
//                    }else if (wuliuUrl.startsWith("//tradearchive.taobao.com")){
//                        Elements simpleList = wuliuDoc.getElementsByClass("simple-list");
//                        if (simpleList != null && simpleList.size() > 0){
//                            Elements trs = simpleList.first().getElementsByTag("tr");
//                            Elements receiverTds = trs.get(2).getElementsByTag("td");
//                            String receiverInfo = receiverTds.get(1).text();
//                            String receiverInfos[] = receiverInfo.split(",");
//                            Elements wayTds = trs.get(3).getElementsByTag("td");
//                            String deliverWay = wayTds.get(1).text();//运送方式
//                            Elements companyTds = trs.get(4).getElementsByTag("td");
//                            String company = companyTds.get(1).text();//公司
//                            Elements waybillNumTds = trs.get(5).getElementsByTag("td");
//                            String waybillNum = companyTds.get(1).text();//运单编号
//
//                        }
//                    }
//
//                }
                    orderInfos.add(orderInfo);
                }
            }
        }
        return orderInfos.toJSONString();
    }

}





